import { useState, useRef, useEffect } from 'react';
import { connect } from 'umi';
import { Radio, Tooltip, Select, InputNumber } from 'antd';

import { question, sell, buy, maxPrice, minPrice, tradeUnit, upHide, downShow } from '@/assets';
import { useTRState } from '#/utils/trHooks';
import { TradeStrategy } from '@/pages/Tianji/TenDaysCentralizedBidding/constant.js';

import styles from './index.less';
import UnitDetailModal from '../UnitDetailModal';
import TradeTable from '../TradeTable';
import SelectStations from '../SelectStations';
import { DownSquareOutlined, UpSquareOutlined } from '@ant-design/icons';

const { Option } = Select;

function ProgramSetting({
  currentProgramInfo,
  selectedUnitInfo,
  selectedRowKeys,
  dispatch,
  is_SD,
  maxValue,
}) {
  const unitDetailModalRef = useRef(),
    [power, setPower] = useState({
      type: 1, // 0：固定值（MW·h）、1：装机容量（MW·h）、2、交易限额（元/MW·h）
      value: 0,
    }),
    [showTradeUnitList, setShowTradeUnitList] = useState(false);

  const changePowerType = (type) => {
    let obj = JSON.parse(JSON.stringify(power));
    obj.type = type;
    obj.value = 0;
    setPower(obj);
  };

  const changePowerValue = (value) => {
    let obj = JSON.parse(JSON.stringify(power));
    obj.value = value;
    setPower(obj);
  };

  // 一键卖出
  const setToSell = () => {
    let data = JSON.parse(JSON.stringify(currentProgramInfo));
    data.hourOrderInfoList.forEach((item) => {
      if (selectedRowKeys.indexOf(item.hourOrder) !== -1) {
        item.tradeStrategy = TradeStrategy.SELL;
        // 如果价格在限价范围之外，则设置为最低价
        if (item.firstPrice > item.upperPrice || item.firstPrice < item.lowerPrice) {
          item.firstPrice = item.lowerPrice;
        }
        if (item.secondPrice > item.upperPrice || item.secondPrice < item.lowerPrice) {
          item.secondPrice = item.lowerPrice;
        }
      }
    });
    dispatch({
      type: 'tenDaysCentralizedBidding/editProgramInfoEffect',
      payload: data,
    });
  };

  // 一键买入
  const setToBuy = () => {
    let data = JSON.parse(JSON.stringify(currentProgramInfo));
    data.hourOrderInfoList.forEach((item) => {
      if (selectedRowKeys.indexOf(item.hourOrder) !== -1) {
        item.tradeStrategy = TradeStrategy.BUY;
        // 如果价格在限价范围之外，则设置为最低价
        if (item.firstPrice > item.upperPrice || item.firstPrice < item.lowerPrice) {
          item.firstPrice = item.lowerPrice;
        }
        if (item.secondPrice > item.upperPrice || item.secondPrice < item.lowerPrice) {
          item.secondPrice = item.lowerPrice;
        }
      }
    });
    dispatch({
      type: 'tenDaysCentralizedBidding/editProgramInfoEffect',
      payload: data,
    });
  };

  // 一键最高价
  const setToMax = () => {
    let data = JSON.parse(JSON.stringify(currentProgramInfo));
    data.hourOrderInfoList.forEach((item) => {
      if (selectedRowKeys.indexOf(item.hourOrder) !== -1) {
        item.firstPrice = item.secondPrice = item.upperPrice;
      }
    });
    dispatch({
      type: 'tenDaysCentralizedBidding/editProgramInfoEffect',
      payload: data,
    });
  };

  // 一键最低价
  const setToMin = () => {
    let data = JSON.parse(JSON.stringify(currentProgramInfo));
    data.hourOrderInfoList.forEach((item) => {
      if (selectedRowKeys.indexOf(item.hourOrder) !== -1) {
        item.firstPrice = item.secondPrice = item.lowerPrice;
      }
    });
    dispatch({
      type: 'tenDaysCentralizedBidding/editProgramInfoEffect',
      payload: data,
    });
  };

  // 批量设置
  const setCheckedPower = () => {
    let data = JSON.parse(JSON.stringify(currentProgramInfo));
    data.hourOrderInfoList.forEach((item) => {
      if (selectedRowKeys.indexOf(item.hourOrder) !== -1) {
        item.submitType = power.type;
        item.firstSubmitPower = power.value;
      }
    });
    dispatch({
      type: 'tenDaysCentralizedBidding/editProgramInfoEffect',
      payload: data,
    });
  };

  const switchAdjust = () => {
    let data = JSON.parse(JSON.stringify(currentProgramInfo));
    data.programInfo.adjust = !data.programInfo.adjust;
    dispatch({
      type: 'tenDaysCentralizedBidding/editProgramInfoEffect',
      payload: data,
    });
  };

  return (
    <div className={styles.programSetting}>
      <div className={styles.stationsAndOperate}>
        <div className={styles.stations}>
          <SelectStations />
        </div>
        <div className={styles.operate}>
          <div className={styles.acceptLimitAdjust}>
            {!is_SD ? (
              <Radio checked={currentProgramInfo.programInfo?.adjust} onClick={switchAdjust}>
                接受限额调剂
              </Radio>
            ) : (
              ''
            )}
            <Tooltip
              placement="bottom"
              title={
                <span>
                  勾选本项，平台不会对申报超额情况报错提醒，并会自动将超额申报值调整为最大限额值；
                  <br />
                  不勾选本项，申报超限额会报错并无法保存。
                </span>
              }
            >
              <img className={styles.icon} src={question} />
            </Tooltip>
          </div>
          <div className={`${styles.setTradeDirection} border-radius-5`}>
            <div className={styles.setToSell} onClick={setToSell}>
              <img src={sell} />
              <span className={styles.text}>一键卖出</span>
            </div>
            <div className={styles.setToBuy} onClick={setToBuy}>
              <img src={buy} />
              <span className={styles.text}>一键买入</span>
            </div>
          </div>
          <div className={`${styles.setTradePrice} border-radius-5`}>
            <div className={styles.setToMax} onClick={setToMax}>
              <img src={maxPrice} />
              <span className={styles.text}>一键最高价</span>
            </div>
            <div className={styles.setToMin} onClick={setToMin}>
              <img src={minPrice} />
              <span className={styles.text}>一键最低价</span>
            </div>
          </div>
          <div className={`${styles.setPower} border-radius-5`}>
            <Radio
              checked={power.type === 1 || power.type === 2}
              onClick={() => {
                changePowerType(1);
              }}
            />
            <Select
              value={power.type === 0 ? 1 : power.type}
              bordered={false}
              onChange={(type) => changePowerType(type)}
              disabled={power.type === 0}
              showArrow={!is_SD}
            >
              <Option className={styles.powerTypeOption} value={1}>
                装机容量
              </Option>
              {!is_SD ? (
                <Option className={styles.powerTypeOption} value={2}>
                  交易限额
                </Option>
              ) : (
                ''
              )}
            </Select>
            <span className={styles.label}>比例</span>
            <InputNumber
              min={0}
              max={is_SD ? 100 : 50}
              precision={0}
              className={styles.value}
              value={power.type === 1 || power.type === 2 ? power.value * 100 : 0}
              onChange={(value) => {
                changePowerValue(value / 100);
              }}
              disabled={power.type === 0}
            />
            <div className={styles.splitLine} />
            <Radio
              checked={power.type === 0}
              onClick={() => {
                changePowerType(0);
              }}
            />
            <span className={styles.label}>固定值</span>
            <InputNumber
              min={0}
              precision={3}
              className={styles.value}
              max={is_SD ? maxValue : Number.MAX_SAFE_INTEGER}
              value={power.type === 0 ? power.value : 0}
              onChange={(value) => {
                const v = is_SD ? Math.floor(value / 10) * 10 : value;
                changePowerValue(v);
              }}
              disabled={power.type === 1 || power.type === 2}
            />
            <div className={styles.btn} onClick={setCheckedPower}>
              批量设置
            </div>
          </div>
        </div>
      </div>
      <div className={`${styles.tradeUnitList} border-radius-5`}>
        <img className={styles.tradUnitIcon} src={tradeUnit} />
        <div className={`${styles.tradUnitText} ${showTradeUnitList ? styles.show : ''}`}>
          <span className={styles.label}>交易单元: </span>
          <span
            className={styles.value}
            onClick={() => {
              if (is_SD) return;
              unitDetailModalRef.current.initHandle();
            }}
          >
            {selectedUnitInfo.unitList.map((item) => item.stationTitle).join('、')}
          </span>
        </div>
        {/* <img
          className={styles.showIcon}
          src={showTradeUnitList ? upHide : downShow}
          onClick={() => {
            setShowTradeUnitList(!showTradeUnitList);
          }}
        /> */}
        {showTradeUnitList ? (
          <UpSquareOutlined
            onClick={() => setShowTradeUnitList(!showTradeUnitList)}
            className={styles.showIcon}
          />
        ) : (
          <DownSquareOutlined
            onClick={() => setShowTradeUnitList(!showTradeUnitList)}
            className={styles.showIcon}
          />
        )}
      </div>
      <TradeTable is_SD={is_SD} />
      <UnitDetailModal ref={unitDetailModalRef} />
      {!currentProgramInfo.editPermission ||
      currentProgramInfo.programInfo.status === 1 ||
      currentProgramInfo.programInfo.status === 2 ? (
        <div className={styles.cover} />
      ) : (
        ''
      )}
    </div>
  );
}

export default connect(({ tenDaysCentralizedBidding }) => ({
  currentProgramInfo: tenDaysCentralizedBidding.currentProgramInfo,
  selectedRowKeys: tenDaysCentralizedBidding.selectedRowKeys,
  maxValue: tenDaysCentralizedBidding.maxValue,
}))(ProgramSetting);
